import { HTTP } from '../utils/http'
import mpx from '@mpxjs/core'
import apiProxy from '@mpxjs/api-proxy'
import globalStore from '~/store/globalData'
import wxApi from '~/utils/wxApi'
import util from '~/utils/util'

mpx.use(apiProxy, {
  usePromise: true
})

class LoginModel extends HTTP {
  // 斗米的登录
  async _login(data = {}) {
    const res = await this.request({
      url: '/sea/api/1.0/client/v1/xinshui/user/thirdlogin',
      data,
      method: 'POST'
    })
    return res
  }

  // 第三方小程序进入斗米登录
  async _thirdLogin(data = {}) {
    const res = await this.request({
      url: '/sea/api/1.0/client/v1/xinshui/user/thirdTokenLogin',
      data,
      method: 'POST'
    })
    return res
  }

  // 获取用户信息
  async getUserInfo(data = {}) {
    const res = await this.request({
      url: '/sea/api/1.0/client/v1/xinshui/user/info',
      data,
      method: 'POST'
    })
    return res
  }

  /**
   * 通过手机号授权方式登录
   * @param {object} event
   */
  async mobile2login({ detail: { errMsg, encryptedData, iv } }) {
    return new Promise(async (resolve, reject) => {
      const that = this
      if (errMsg === 'getPhoneNumber:ok') {
        try {
          wx.showLoading({
            title: '登录中',
            mask: true
          })
          let param = {
            mobile: JSON.stringify({
              errMsg,
              encryptedData,
              iv
            })
          }
          const result = await wxApi.doumiCheckSession() // 验证微信session是否过期
          if (result == 'fail') {
            const res = await mpx.login()
            wx.setStorageSync('code', res.code)
            param = { ...param, ...{ code: res.code } }
          } else {
            const code = wx.getStorageSync('code')
            param = { ...param, ...{ code } }
          }
          await that.loginToDoumi(param) // 登录斗米
          wx.hideLoading()
          return resolve()
        } catch (error) {
          wx.hideLoading()
        }
      } else {
        util.showToast('您已拒绝授权,请重试')
      }
    })
  }

  /**
   * 第三方小程序跳转过来方式登录
   */
  async loginByThirdParty(params) {
    return new Promise(async (resolve, reject) => {
      const that = this
      try {
        const result = await that.loginToDoumi(params, 'third') // 登录斗米
        return resolve(result)
      } catch (error) {
        // util.showToast(error)
        wx.showModal({
          title: '登录错误，请退出重试',
          content: error,
          showCancel: false,
          success: (res) => {
            mpx.navigateBackMiniProgram({
              extraData: {
                result: error
              },
              success(res) {
                // 返回成功
              }
            })
          }
        })
      }
    })
  }

  /**
   * 上传斗米服务器
   */
  async loginToDoumi(param, loginType) {
    let loginRes
    if (loginType === 'third') {
      loginRes = await this._thirdLogin(param)
    } else {
      loginRes = await this._login(param)
    }
    // const loginRes = await this._login(param)
    const { errno, errmsg, data } = loginRes.data
    console.log(loginRes)
    if (errno == 0) {
      // 登录成功
      const cookieStr =
        loginRes.header['Set-Cookie'] || loginRes.header['set-cookie']
      if (cookieStr && cookieStr.length > 0) {
        const cookie = cookieStr.split(';')
        const userInfo = {
          cookie: cookie[0],
          mobile: data.phoneNumber
        }
        globalStore.commit('setUserInfo', userInfo)
        wx.setStorageSync('userInfoNew', userInfo)
      }
      return Promise.resolve(data)
    } else {
      // wx.showToast({
      //   title: errmsg,
      //   icon: 'none'
      // })
      return Promise.reject(errmsg)
    }
  }
}

export { LoginModel }
